package cn.zhuama.org.controller;

import cn.zhuama.basic.util.AjaxResult;
import cn.zhuama.basic.util.PageList;
import cn.zhuama.org.domain.Book;
import cn.zhuama.org.domain.Bookde;
import cn.zhuama.org.query.BookQuery;
import cn.zhuama.org.service.BookService;
import cn.zhuama.org.service.BookdeService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    BookService bookService;

    @Autowired
    BookdeService bookdeService;
    //分页
    @PostMapping
    public PageList<Book> queryPage(@RequestBody BookQuery bookQuery){
        return bookService.queryPage(bookQuery);
    }

        //新增//修改
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Book book){
        try {
            if(book.getBook_id()==null){
                bookService.add(book);
            }else {
                bookService.update(book);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }

    @DeleteMapping("/{id}")// @return   delete http://localhost:8080/department/1
    @ApiOperation(value = "删除接口")
    @Transactional
    public AjaxResult del(@PathVariable("id") Long id){
        try {
                    Book d = bookService.queryOne(id);
                    List<Bookde> bd = bookdeService.findAll();
                    for(Bookde de:bd){
                        if(de.getDno().equals(d.getBookname())){
                            bookdeService.del(de.getDid());
                        }
                    }
            bookService.del(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

    @PatchMapping
    @ApiOperation(value = "批量删除接口")
    public AjaxResult patchDelete(@RequestBody List<Long> ids){

        try {
            List<Book> books = new ArrayList<>();
            for(Long l:ids){
                books.add(bookService.queryOne(l));
            }
            List<Bookde> bookdes = bookdeService.findAll();
            for(Book b:books) {
                for (Bookde de : bookdes) {
                    if (de.getDno().equals(b.getBookname())) {
                        bookdeService.del(de.getDid());
                    }
                }
            }
            bookService.patchDel(ids);
            return  new AjaxResult(true);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }


    //查所有
    @GetMapping
    public List<Book> findAll(){
        return bookService.findAll();
    }

//


//




}
